<template>
  <!-- 异常趋势分析 - 月报 -->
  <a-spin :spinning="loading">
    <div class="AbnormalTrendMonthly" ref="containerRef">
      <div class="titleBar">
        <div class="title">
          异常趋势分析 - 月报
          <div class="dateRange">
            <a-date-picker
              v-model:value="timeData"
              picker="month"
              :disabled-date="disabledDate"
              style="margin-right: 8px;"
              size="small"
            />
            <a-button
              size="small"
              type="primary"
              class="queryBtn"
              @click="outageDashboardData"
              >查询</a-button
            >
            <a-button size="small" type="link" @click="handleReset"
              >重置</a-button
            >
          </div>
        </div>
      </div>
      <div class="content">
        <div class="topChart">
          <div ref="horizontalBarChartRef" class="chartContainer"></div>
        </div>
        <div
          class="bottomChart tableContainer"
          :style="{ width: containerWidth + 'px' }"
        >
          <a-table
            :columns="columns"
            :data-source="tableData"
            :pagination="false"
            size="small"
            :scroll="{ x: 1120, y: 140 }"
            :row-key="(record) => record.id"
          >
            <template #bodyCell="{ column, index }">
              <template v-if="column.key === 'index'">
                {{ index + 1 }}
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup>

import * as echarts from "echarts";
import dayjs from "dayjs";
const props = defineProps({
  pageType: {
    type: String,
  },
});
const timeData = ref(dayjs().subtract(1, "month")); // 默认选择上个月
const $api = inject("$api");
const disabledDate = (current) => {
  // 禁用当前月及之后的月份
  return (
    current && current.isAfter(dayjs().startOf("month").subtract(1, "day"))
  );
};
const chartData = ref([]);
// 图表引用
const horizontalBarChartRef = ref(null);
// 图表实例
let horizontalBarChart = null;
const containerWidth = ref(0);
const containerRef = ref(null);
const updateContainerWidth = () => {
  if (containerRef.value) {
    containerWidth.value = containerRef.value.offsetWidth - 24;
  }
};
const columns = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    width: 60,
    align: "center",
    ellipsis: true,
  },
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 120,
    ellipsis: true,
  },
  {
    title: "所属厂商",
    dataIndex: "supplierName",
    key: "supplierName",
    width: 100,
    ellipsis: true,
  },
  {
    title: "故障现象描述",
    dataIndex: "faultDesc",
    key: "faultDesc",
    width: 220,
    ellipsis: true,
  },
  {
    title: "缺陷及故障处理方法描述",
    dataIndex: "faultDealDesc",
    key: "faultDealDesc",
    width: 300,
    ellipsis: true,
  },
  {
    title: "故障类别",
    dataIndex: "faultTypeName",
    key: "faultTypeName",
    width: 120,
  },
  {
    title: "故障细分",
    dataIndex: "faultSegmentName",
    key: "faultSegmentName",
    width: 120,
  },
  {
    title: "故障归属",
    dataIndex: "faultBelongName",
    key: "faultBelongName",
    width: 120,
  },
  {
    title: "故障开始时间",
    dataIndex: "faultStartDate",
    key: "faultStartDate",
    width: 160,
  },
  {
    title: "是否导致项目停运",
    dataIndex: "causeProjectShutdownStr",
    key: "causeProjectShutdownStr",
    width: 120,
  },
  {
    title: "故障结束时间",
    dataIndex: "faultEndDate",
    key: "faultEndDate",
    width: 160,
  },
];
const tableData = ref([]);
const selectedBarIndex = ref(-1);
const initHorizontalBarChart = () => {
  if (!horizontalBarChartRef.value) return;
  if (horizontalBarChart) {
    horizontalBarChart.dispose();
  }
  horizontalBarChart = echarts.init(horizontalBarChartRef.value);

  // 根据选中月份计算天数
  const selectedMonth = timeData.value;
  const daysInMonth = selectedMonth.daysInMonth();
  const xAxisData = Array.from({ length: daysInMonth }, (_, i) => i + 1);

  let values = [];
  const chartDataMap = {};
  if (chartData.value && Array.isArray(chartData.value)) {
    chartData.value.forEach((item) => {
      if (item.day) {
        chartDataMap[item.day] = item;
      }
    });
  }

  // 根据天数生成对应的values数组
  for (let day = 1; day <= daysInMonth; day++) {
    if (chartDataMap[day]) {
      values.push(chartDataMap[day].dayCount || 0);
    } else {
      values.push(0);
    }
  }
  const defaultColor = new echarts.graphic.LinearGradient(0, 1, 0, 0, [
    { offset: 0, color: "rgba(22, 168, 251, 1)" },
    { offset: 1, color: "rgba(76, 86, 239, 1)" },
  ]);
  const highlightColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: "#FF9F43" },
    { offset: 1, color: "#FF7A00" },
  ]);
  // 移除默认选中逻辑，所有柱子都显示默认颜色
  const seriesData = values.map((value, index) => ({
    value,
    itemStyle: {
      color: defaultColor,
      borderRadius: [4, 4, 0, 0],
    },
  }));
  // 检查数据是否存在
  if (seriesData.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    horizontalBarChart.setOption(option);
    return;
  }
  // 设置默认不选中任何柱子
  selectedBarIndex.value = -1;

  // 汇总所有天的faultDealDtoList数据
  const allFaultData = [];
  if (chartData.value && Array.isArray(chartData.value)) {
    chartData.value.forEach((dayData) => {
      if (dayData.faultDealDtoList && Array.isArray(dayData.faultDealDtoList)) {
        dayData.faultDealDtoList.forEach((item, index) => {
          allFaultData.push({
            ...item,
            key: `day${dayData.day}-${index}`,
            id: `day${dayData.day}-${index}`,
          });
        });
      }
    });
  }
  
  // 默认显示所有faultDealDtoList数据
  tableData.value = allFaultData;

  const maxValue = Math.max(...values);
  let yAxisMax, yAxisInterval;

  if (maxValue <= 1) {
    yAxisMax = 1;
    yAxisInterval = 1;
  }

  const option = {
    title: {
      text: `${timeData.value.format("YYYY年M月")} - ${props.pageType === "Unplanned" ? "非计划" : "计划"}故障趋势图`,
      left: "center",
      top: 0,
      textStyle: {
        color: "#e2e8f0",
        fontSize: 14,
        fontWeight: "bold",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
      formatter: function (params) {
        if (params && params.length > 0) {
          const day = params[0].name;
          const value = params[0].value;
          return `${day}号<br/>故障次数: ${value}`;
        }
        return "";
      },
    },
    grid: {
      top: "40",
      left: "3%",
      right: "0",
      bottom: "0",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      data: xAxisData,
    },
    yAxis: {
      type: "value",
      min: 0,
      max: yAxisMax,
      interval: yAxisInterval,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        formatter: function (value) {
          return Math.round(value);
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "故障次数",
        type: "bar",
        barWidth: 20,
        data: seriesData,
        itemStyle: {
          color: defaultColor,
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(35, 145, 255, 0.1)",
        },
      },
    ],
  };

  horizontalBarChart.setOption(option);
  horizontalBarChart.on("click", function (params) {
    if (params.componentType === "series" && params.seriesType === "bar") {
      const clickedDay = params.name;
      const clickedDataIndex = params.dataIndex;
      const currentOption = horizontalBarChart.getOption();
      const currentSeriesData = currentOption.series[0].data;

      // 更新表格数据为当前选中天的faultDealDtoList
      const selectedDayData = chartDataMap[clickedDay];
      if (
        selectedDayData &&
        selectedDayData.faultDealDtoList &&
        Array.isArray(selectedDayData.faultDealDtoList)
      ) {
        tableData.value = selectedDayData.faultDealDtoList.map(
          (item, index) => ({
            ...item,
            key: `${clickedDay}-${index}`,
            id: `${clickedDay}-${index}`,
          })
        );
      } else {
        tableData.value = [];
      }

      if (selectedBarIndex.value === clickedDataIndex) {
        currentSeriesData[clickedDataIndex].itemStyle.color = defaultColor;
        selectedBarIndex.value = -1;
        // 重置为默认表格数据
        tableData.value = allFaultData;
      } else {
        currentSeriesData.forEach((item, index) => {
          if (index === clickedDataIndex) {
            item.itemStyle.color = highlightColor;
          } else {
            item.itemStyle.color = defaultColor;
          }
        });
        selectedBarIndex.value = clickedDataIndex;
      }
      // 更新图表配置
      horizontalBarChart.setOption({
        series: [
          {
            data: currentSeriesData,
          },
        ],
      });
    }
  });
};

const handleResize = () => {
  horizontalBarChart && horizontalBarChart.resize();
  updateContainerWidth();
};
const loading = ref(false);
const outageDashboardData = async () => {
  const params = {
    planShutdown: props.pageType === "Unplanned" ? 0 : 1,
    dashboardYearMonth: timeData.value.format("YYYY-MM"),
    dashboardType: "4", // 1：故障类别分析 2：故障归属分析 3：异常趋势分析-年报 4：异常趋势分析-月报
  };
  loading.value = true;
  const res = await $api.faultDealDashboard(4, params);
  loading.value = false;
  if (
    res.code === 0 &&
    res.data?.faultDealAnalyzeMonthDtoList &&
    Array.isArray(res.data.faultDealAnalyzeMonthDtoList)
  ) {
    chartData.value = res.data.faultDealAnalyzeMonthDtoList;
  } else {
    chartData.value = [];
  }

  tableData.value = [];
  selectedBarIndex.value = -1;

  await nextTick();
  initHorizontalBarChart();
};
const handleReset = async () => {
  timeData.value = dayjs().subtract(1, "month");
  await outageDashboardData();
  initHorizontalBarChart();
};
onMounted(async () => {
  await outageDashboardData();
  initHorizontalBarChart();
  updateContainerWidth();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  horizontalBarChart && horizontalBarChart.dispose();
});
</script>

<style scoped lang="less">
.AbnormalTrendMonthly {
  flex: 1;
  min-width: 0;
  height: 480px;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .timeSelect {
    padding: 0 8px;
    width: 140px;
  }
  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
    overflow: hidden;
    padding-top: 10px;

    .topChart {
      width: 100%;
      height: 210px;
      display: flex;
      flex-direction: column;
      gap: 10px;

      .chartContainer {
        width: 100%;
        height: 100%;
      }
    }

    .bottomChart {
      width: 100%;
      height: 55%;
      min-width: 0;
      .chartContainer {
        width: 100%;
        height: 100%;
      }
    }
    .tableContainer {
      min-width: 0;
      height: 150px;
      margin-top: 10px;

      :deep(.ant-table) {
        width: 100%;
        background: transparent;
        color: #e2e8f0;

        .ant-table-container {
          min-width: 0;
        }

        .ant-table-content {
          overflow-x: auto;
        }

        .ant-table-thead > tr > th {
          background: #1e293b;
          color: #e2e8f0;
          border-bottom: 1px solid #334155;
          padding: 8px 12px;
          font-size: 12px;
          height: 40px;
          line-height: 24px;
        }

        .ant-table-tbody > tr > td {
          border-bottom: 1px solid #334155;
          color: #94a3b8;
          padding: 6px 12px;
          font-size: 12px;
        }

        .ant-table-body {
          overflow-x: auto !important;

          &::-webkit-scrollbar {
            width: 6px;
            height: 6px;
          }

          &::-webkit-scrollbar-thumb {
            background: #475569;
            border-radius: 3px;
          }

          &::-webkit-scrollbar-track {
            background: #1e293b;
          }
        }
      }
    }
  }
}
</style>
